import React, { Component } from "react";
import { inject, observer } from "mobx-react";
import { Icon, ActivityIndicator, Checkbox, tools, Tabs, Button, WhiteSpace, } from "weaver-mobile";
import { TabPage, ListViewPage, RouteLayout, DocumentTitle } from "weaver-mobile-page";
import { withRouter, Route } from 'react-router-dom';
import SearchConponent from "../common/SearchConponent";
import * as allFun from "../../../workflowForm/util/forwardPage";
import ResonModal from "./resonModal";
import SendOtherBrowser from "./sendOtherBrowser";
import CheckReceiveDoc from "./checkReceiveDoc";
import NoRightCom from "../common/NoRightComponent";
const Item = TabPage.Item;
const { getLabel } = tools;
const ButtonGroup = RouteLayout.ButtonGroup;
const AgreeItem = Checkbox.AgreeItem;

@inject("docExchangeStore")
@withRouter
@observer
class DocExchange extends Component {

  static defaultProps = {
    prefixCls: "odoc-exchange",
  }

  componentDidMount() {
    const { docExchangeStore } = this.props;
    docExchangeStore.getTabs();
    //直接打开本页面
    docExchangeStore.getList();

  }

  componentWillUnmount() {
    const { docExchangeStore } = this.props;
    docExchangeStore.initData();
  }

  render() {
    const { prefixCls, docExchangeStore, location: { pathname, query }, history } = this.props;
    const { exchangeType, visible, selectedTab, setState, tabs, tabClick, number, loading, showCheck, isSelectedAll, selectedRowKeys, hasRight,
      selectALL, selectNone, showListCheck, modalVisible, btnType, reasonCheck, getList, checkReceiveList, textareaValue } = docExchangeStore;

    if (!hasRight) {
      return <NoRightCom />
    }

    const topTabs = [
      { title: '发送公文', key: 0 },
      { title: '接收公文', key: 1 },
    ];
    const conditionParams = {
      menuType: exchangeType == 1 ? 'receiveDoc' : '',
      isInnerChange: 1
    }
    let overlay = [];
    let isShowPopover = false;
    if (exchangeType == 0) {
      if (selectedTab == '0') {
        isShowPopover = true;
        overlay.push(<Item key="0" value="batchSend" data-seed="logId" ><span >{getLabel(517319, "批量发送")}</span></Item>)
      } else if (selectedTab == '1') {
        isShowPopover = true;
        overlay.push(<Item key="0" value="batchSendOther" data-seed="logId"><span >{getLabel('', "批量发送其他单位")}</span></Item>)
        overlay.push(<Item key="1" value="batchDel" data-seed="logId"><span >{getLabel('', "批量作废")}</span></Item>)
      } else if (selectedTab == '2' || selectedTab == '3' || selectedTab == '4') {
        isShowPopover = true;
        overlay.push(<Item key="0" value="batchSendOther" data-seed="logId"><span >{getLabel('', "批量发送其他单位")}</span></Item>)
      }
    } else if (exchangeType == 1) {
      // overlay.push(<Item key="0" value="receive" data-seed="logId"><span >{getLabel(18526, "接收")}</span></Item>)
      if (selectedTab == '0') {
        isShowPopover = true;
        overlay.push(
          <Item key="1" value="batchReceive" style={{ whiteSpace: 'nowrap' }}><span >{getLabel(387687, "批量签收")}</span></Item>,
          <Item key="2" value="batchRejection" style={{ whiteSpace: 'nowrap' }}><span >{getLabel(387688, "批量拒收")}</span></Item>,
          <Item key="3" value="batchSendBack" style={{ whiteSpace: 'nowrap' }}><span >{getLabel(83423, "批量退回")}</span></Item>,
        )
      } else if (selectedTab == '1') {
        // isShowPopover = true;
        // overlay.push(<Item key="1" value="batchSendBack" style={{ whiteSpace: 'nowrap' }}><span >{getLabel(83423, "批量退回")}</span></Item>)
      }
    }
    // const isShowPopover = (exchangeType == 0 && selectedTab != '5') ? false : true;
    const titles = [
      { match: /^\/docExchange/i, title: () => getLabel('', "内部交换") },
      { match: /^\/docExchange\/receiveDoc/i, title: () => getLabel('', "内部交换") },
    ];
    return (
      <div className={`${prefixCls}`}>
        <DocumentTitle data={titles} defaultTitle="" />
        <Tabs
          tabs={topTabs}
          onChange={(tab, index) => this.changeTopTab(tab, index)}
          page={exchangeType}
          tabBarUnderlineStyle={{ display: 'none' }}
        />
        <TabPage
          className={`${prefixCls}-tab-page`}
          tabProps={{
            onTabClick: (tab) => tabClick(tab),
            initialPage: number,
            animated: false,
            page: selectedTab
          }}
          // span={[6, 1]}
          tabs={tabs}
          popover={isShowPopover}
          popoverProps={{
            overlay,
            onVisibleChange: this.handleVisibleChange.bind(this),
            visible,
            onSelect: (node, index) => {
              const type = node.props.value;
              setState({ visible: false, showCheck: true, btnType: type });
              showListCheck();
            },
          }}
        />

        {exchangeType == 0 && <SearchConponent
          getCondition={{
            url: "/api/offical/sendDoc/condition",
            params: conditionParams
          }}// 高级搜索form表单接口参数  默认是 没有url，post，没有参数
          pathname={pathname} //原路由地址
          history={history}
          extraButton={["advanced"]} //搜索类型
          baseSearchKey={"doctitle"} // 基本搜索的key 数据同步用
          getSearchData={this.getSearchData}
          title={getLabel('', '请输入流程标题')}
          showHotSearch={true}
        />}

        {exchangeType == 1 && <SearchConponent
          getCondition={{
            url: "/api/offical/receiveDoc/condition",
            params: conditionParams
          }}// 高级搜索form表单接口参数  默认是 没有url，post，没有参数
          pathname={pathname} //原路由地址
          history={history}
          extraButton={["advanced"]} //搜索类型
          baseSearchKey={"documentTitle"} // 基本搜索的key 数据同步用
          getSearchData={this.getSearchData}
          title={getLabel('503576', '请输入公文标题')}
          showHotSearch={true}
        />}

        <div style={{ height: `calc(100% - 135px)` }}>
          {showCheck && <div className="list-selectedMsg" >
            <span className="selectedMsg-cancel" onClick={() => {
              setState({ showCheck: false });
              selectNone();
            }}>{getLabel(31129, '取消')}</span>
            <span>{getLabel(500274, "已选择")}{" " + selectedRowKeys.length + " "}{getLabel(18256, "条") + getLabel('30045', '流程')}</span>
            <span className="selectedMsg-all" onClick={() => {
              isSelectedAll ? selectNone() : selectALL()
            }}> {isSelectedAll && getLabel(31129, '取消')}{getLabel(556, '全选')}</span>
          </div>}
          {/* 处理有三个滑动按钮 */}
          {exchangeType == '0' && selectedTab == '1' && this.getTableList()}
          {/* 处理有单个滑动按钮、无滑动按钮 */}
          {exchangeType == '0' && selectedTab != '1' && this.getsendFirstList()}
          {exchangeType == '1' && this.getTableList()}
          {loading && <ActivityIndicator
            toast
            text={getLabel(500408, "加载中...")}
            animating={loading}
          />}
          {showCheck && this.getBatchBtn()}
          {modalVisible && <ResonModal modalVisible={modalVisible} btnType={btnType} setState={setState} reasonCheck={reasonCheck} textareaValue={textareaValue} />}

          <SendOtherBrowser historyProp={history} />

          <Route
            key={checkReceiveList.id}
            path={checkReceiveList.path}
            render={(props) => {
              return (
                <RouteLayout>
                  <div
                    key="wmPoutePageDemo"
                    className="wm-route-layout"
                  >
                    <CheckReceiveDoc historyProp={history} />
                  </div>
                </RouteLayout>
              )
            }}
          />

        </div>
      </div>
    )
  }
  changeTopTab = (tab, index) => {
    const { docExchangeStore, history } = this.props;
    docExchangeStore.changeTypeTab(tab);
    if (index == '0') {
      history.push('/docExchange');
    } else {
      history.push('/docExchange/receiveDoc');
    }
  }

  getBatchBtn = () => {
    const { isSelectedAll, selectedRowKeys, btnType } = this.props.docExchangeStore;
    const btnDisabled = isSelectedAll ? false : selectedRowKeys.length > 0 ? false : true;
    return (
      <div className="selectedMsg-send" >
        {btnType == 'batchSend' && <Button disabled={btnDisabled} type="primary" onClick={() => this.clickBttomBtn(btnType)} className={btnDisabled ? 'btnDisabled' : ''} >
          {getLabel(517319, "批量发送")}
        </Button>}
        {btnType == 'batchSendOther' && <Button disabled={btnDisabled} type="primary" onClick={() => this.clickBttomBtn(btnType)} className={btnDisabled ? 'btnDisabled' : ''} >
          {getLabel('', "批量发送其他单位")}
        </Button>}
        {btnType == 'batchDel' && <Button disabled={btnDisabled} type="primary" onClick={() => this.clickBttomBtn(btnType)} className={btnDisabled ? 'btnDisabled' : ''} >
          {getLabel('', "批量作废")}
        </Button>}
        {btnType == 'batchReceive' && <Button disabled={btnDisabled} type="primary" onClick={() => this.clickBttomBtn(btnType)} className={btnDisabled ? 'btnDisabled' : ''} >
          {getLabel(387687, "批量签收")}
        </Button>}
        {btnType == 'batchRejection' && <Button disabled={btnDisabled} type="primary" onClick={() => this.clickBttomBtn(btnType)} className={btnDisabled ? 'btnDisabled' : ''} >
          {getLabel(387688, "批量拒收")}
        </Button>}
        {btnType == 'batchSendBack' && <Button disabled={btnDisabled} type="primary" onClick={() => this.clickBttomBtn(btnType)} className={btnDisabled ? 'btnDisabled' : ''} >
          {getLabel(83423, "批量退回")}
        </Button>}
      </div>
    )
  }
  clickBttomBtn = (btnType) => {
    const { docExchangeStore, history } = this.props;
    const { sendDoc, setState, onSigninDoc } = docExchangeStore;
    if (btnType == 'batchSend') {
      sendDoc();
    } else if (btnType == 'batchSendOther') {
      history.push(docExchangeStore.sendOtherBrowser.path);
    } else if (btnType == 'batchDel') {
      setState({
        modalVisible: true
      })
    } else if (btnType == 'batchReceive') {
      onSigninDoc();
    } else if (btnType == 'batchRejection') {
      setState({
        modalVisible: true
      })
    } else if (btnType == 'batchRejection') {
      setState({
        modalVisible: true
      })
    } else if (btnType == 'batchSendBack') {
      setState({
        modalVisible: true
      })
    }
  }

  handleVisibleChange = bool => {
    const { setState } = this.props.docExchangeStore;
    setState({ visible: bool });
  };

  getSearchData = (formParams) => {
    const { docExchangeStore } = this.props;
    docExchangeStore.getList(formParams, true);
  }
  getTableList() {
    const { docExchangeStore, prefixCls } = this.props;
    const { list, showCheck, loading, exchangeType, selectedTab } = docExchangeStore;
    const items =
      <div style={{ height: showCheck ? `calc(100% - 90px)` : '100%', overflow: 'hidden' }}>
        <ListViewPage.Normal
          store={list}
          rowKey='id'
          getTemplate={this.getTemplate}
          //onRowClick={(rowData) => this.forwardPage(rowData)}
          showCheck={showCheck}
          onRowSelect={(selectedRowKeys, c) => this.onRowSelect(selectedRowKeys, c)}
          swipeActionProps={this.getSwipeActionProps(exchangeType, selectedTab)}
          withSwipeAction
          customHeight="100%"
        />
      </div>
    return items;
  }
  getsendFirstList = () => {
    const { docExchangeStore, prefixCls } = this.props;
    const { list, showCheck, loading, exchangeType, selectedTab } = docExchangeStore;
    const items =
      <div style={{ height: showCheck ? `calc(100% - 90px)` : '100%', overflow: 'hidden' }}>
        <ListViewPage.Normal
          customHeight="100%"
          store={list}
          rowKey='idspan'
          getTemplate={this.getTemplate}
          //onRowClick={(rowData) => this.forwardPage(rowData)}
          showCheck={showCheck}
          onRowSelect={(selectedRowKeys, c) => {
            // console.log(c);
            this.onRowSelect(selectedRowKeys, c)
          }}
          swipeActionProps={this.getSwipeActionProps1(exchangeType, selectedTab)}
          withSwipeAction
        />
      </div>
    return items;
  }
  getTemplate = () => {
    const { docExchangeStore, prefixCls } = this.props;
    const { exchangeType, selectedTab } = docExchangeStore;
    const _this = this;
    const sendTemplate = {
      default: [
        {
          key: 'col1',
          configs: [
            {
              key: 'row1',
              render(item) {
                return (
                  <div>
                    <span>{getLabel('', '流程标题') + "："}</span>
                    <span style={{ color: "#0099ff" }} onClick={() => _this.forwardPage(item)} > {item.requestidspan} </span>
                  </div>
                )
              },
              style: { margin: "5px 0" }
            },
            {
              key: 'row2',
              render(item) {
                return (
                  <div>
                    <span>{getLabel('', '发文字号') + "："}</span>
                    <span className={`${prefixCls}-itemColor`} > {item.issued_numspan || item.issued_number_of_documentspan} </span>
                  </div>
                )
              },
              style: { margin: "5px 0" }
            },
            {
              key: 'row3',
              render(item) {
                return (
                  <div>
                    <span>{getLabel('', '收文单位') + "："}</span>
                    <span className={`${prefixCls}-itemColor`} > {
                      selectedTab == '0' ? item.receiveunitspan :
                        selectedTab == '1' || selectedTab == '5' ? item.docIdspan : item.receiveunitnamespan
                    } </span>
                  </div>
                )
              },
              style: { margin: "5px 0" }
            },
            {
              key: 'row4',
              render(item) {
                return (
                  <div>
                    <span>{getLabel('', '处理时间') + "："}</span>
                    <span className={`${prefixCls}-itemColor`} > {item.lastoperatedatespan || item.senddatespan || item.dealdatespan} </span>
                  </div>
                )
              },
              style: { margin: "5px 0" }
            },
            {
              key: 'row5',
              render(item) {
                return (
                  <div>
                    <span>{getLabel('', '当前状态') + "："}</span>
                    <span className={`${prefixCls}-itemColor`} > {item.createrspan || item.send_statusspan || item.doc_statusspan} </span>
                  </div>
                )
              },
              style: { margin: "5px 0" }
            },
            {
              key: 'row6',
              render(item) {
                return (
                  <div>
                    <span>{getLabel('', '处理意见') + "："}</span>
                    <span className={`${prefixCls}-itemColor`} > {item.response_msgspan} </span>
                  </div>
                )
              },
              style: { display: selectedTab != '5' ? 'none' : '', margin: "5px 0" }
            },
          ],
        },
      ],
    };
    const receiveTemplate = {
      default: [
        {
          key: 'col1',
          configs: [
            {
              key: 'row1',
              style: { margin: "5px 0" },
              render(item) {
                return (
                  <div>
                    <span>{getLabel('', '公文标题') + "："}</span>
                    <span style={{ color: (selectedTab == '0' || selectedTab == '1') ? "#0099ff" : '#000' }} onClick={() => _this.clickDocTitle(item)} > {item.document_identifierspan} </span>
                  </div>
                )
              },
            },
            {
              key: 'row2',
              style: { margin: "5px 0" },
              render(item) {
                return (
                  <div>
                    <span>{getLabel('', '发文字号') + "："}</span>
                    <span className={`${prefixCls}-itemColor`} > {item.issued_number_of_documentspan} </span>
                  </div>
                )
              },
            },
            {
              key: 'row3',
              style: { margin: "5px 0" },
              render(item) {
                return (
                  <div>
                    <span>{getLabel('', '来文单位') + "："}</span>
                    <span className={`${prefixCls}-itemColor`} > {item.sending_departmentspan} </span>
                  </div>
                )
              },
            },
            {
              key: 'row4',
              style: { margin: "5px 0", display: selectedTab != '1' ? 'none' : '' },
              render(item) {
                return (
                  <div>
                    <span>{getLabel('', '收文单位') + "："}</span>
                    <span className={`${prefixCls}-itemColor`} > {item.receiver_departmentspan} </span>
                  </div>
                )
              },
            },
            {
              key: 'row5',
              style: { margin: "5px 0" },
              render(item) {
                return (
                  <div>
                    <span>{selectedTab != '1' ? getLabel('', '接收时间') : getLabel('', '签收时间') + "："}</span>
                    <span className={`${prefixCls}-itemColor`} > {item.receive_datespan || item.operate_datespan} </span>
                  </div>
                )
              },
            },
            {
              key: 'row6',
              style: { margin: "5px 0" },
              render(item) {
                return (
                  <div>
                    <span>{getLabel('', '当前状态') + "："}</span>
                    <span className={`${prefixCls}-itemColor`} > {item.receive_statusspan} </span>
                  </div>
                )
              },
            },
            {
              key: 'row7',
              style: { margin: "5px 0", display: selectedTab != '1' ? 'none' : '' },
              render(item) {
                return (
                  <div>
                    <span>{getLabel('', '收文流程') + "："}</span>
                    <span style={{ color: "#0099ff" }} onClick={() => _this.clickWorkflowTitle(item)} > {item.subrequestidspan} </span>
                  </div>
                )
              },
            },
            {
              key: 'row8',
              style: { margin: "5px 0", display: (selectedTab == '0' || selectedTab == '1') ? 'none' : '' },
              render(item) {
                return (
                  <div>
                    <span>{getLabel('', '处理意见') + "："}</span>
                    <span className={`${prefixCls}-itemColor`} > {item.notespan} </span>
                  </div>
                )
              },
            },
          ]
        },
      ],
    };
    return exchangeType == "0" ? sendTemplate : receiveTemplate;
  }

  onRowSelect = (selectedRowKeys, c) => {
    const { setState, setSelectedRequestids } = this.props.docExchangeStore;
    setState({ selectedRowKeys: selectedRowKeys });
    setSelectedRequestids(c);
  }

  getSwipeActionProps1 = (exchangeType, selectedTab) => {
    const { prefixCls, history, docExchangeStore } = this.props;
    const { sendDoc, setState, getSendDocinfo } = docExchangeStore;
    if (exchangeType == "0") {
      if (selectedTab == '0') {
        return ({
          right: [{
            text: getLabel("2083", "发送"),
            onPress: (data) => {
              sendDoc(data.id);
            },
            className: `${prefixCls}-send`,
            style: { width: "100px", background: "#0099ff" },
          }],
        })
      } else if (selectedTab == '2' || selectedTab == '3' || selectedTab == '4') {
        return ({
          right: [{
            text: getLabel("387634", "查看收文情况"),
            onPress: (data) => {
              setState({
                currentId: data.requestid,
                backId: data.id,
                currentName: data.requestidspan,
                documentIdentifier: data.document_identifierspan
              })
              history.push(docExchangeStore.checkReceiveList.path);
              getSendDocinfo();
            },
            className: `${prefixCls}-send`,
            style: { width: "90px", background: "#f59a23" },
          }, {
            text: getLabel("388098", "发送其他单位"),
            onPress: (data) => {
              history.push(docExchangeStore.sendOtherBrowser.path);
              setState({ currentId: data.requestid })
            },
            className: `${prefixCls}-send`,
            style: { width: "90px", background: "#0099ff" },
          }]
        })
      }
    }
  }
  getSwipeActionProps = (exchangeType, selectedTab) => {
    const { prefixCls, history, docExchangeStore } = this.props;
    const { setState, getSendDocinfo, onSigninDoc } = docExchangeStore;
    if (exchangeType == "0") {
      if (selectedTab == '1') {
        return ({
          right: [{
            text: getLabel("387634", "查看收文情况"),
            onPress: (data) => {
              setState({
                backId: data.id,
                currentId: data.requestid,
                currentName: data.requestidspan,
                documentIdentifier: data.document_identifierspan
              })
              history.push(docExchangeStore.checkReceiveList.path);
              getSendDocinfo();
            },
            className: `${prefixCls}-send`,
            style: { width: "90px", background: "#f59a23" },
          }, {
            text: getLabel("15358", "作废"),
            onPress: (data) => {
              setState({
                modalVisible: true,
                currentId: data.id,
                btnType: 'batchDel'
              });
            },
            className: `${prefixCls}-send`,
            style: { width: "50px", background: "#7f7f7f" },
          }, {
            text: getLabel("388098", "发送其他单位"),
            onPress: (data) => {
              history.push(docExchangeStore.sendOtherBrowser.path);
              setState({ currentId: data.requestid })
            },
            className: `${prefixCls}-send`,
            style: { width: "90px", background: "#0099ff" },
          }]
        })
      }
    } else if (exchangeType == '1') {
      if (selectedTab == '0') {
        return ({
          right: [{
            text: getLabel("", "签收"),
            onPress: (data) => {
              onSigninDoc(data.id);
            },
            className: `${prefixCls}-check`,
            style: { width: "60px" },
          }, {
            text: getLabel("", "拒收"),
            onPress: (data) => {
              setState({
                modalVisible: true,
                currentId: data.id,
                btnType: 'batchRejection'
              });
            },
            className: `${prefixCls}-del`,
            style: { width: "60px" },
          }, {
            text: getLabel("", "退回"),
            onPress: (data) => {
              setState({
                modalVisible: true,
                currentId: data.id,
                btnType: 'batchSendBack',
              });
            },
            className: `${prefixCls}-send`,
            style: { width: "60px" },
          }]
        })
      }
    }
  }

  forwardPage(rowData) {
    const { docExchangeStore } = this.props;
    if (docExchangeStore.exchangeType == 0 && !docExchangeStore.showCheck) {
      allFun.forwardViewForm('requestid=' + rowData.requestid + '&f_weaver_belongto_userid=' + rowData.userid, (arg) => {
        docExchangeStore.getList();
      }, "portal")
    }
  }

  clickDocTitle = (item) => {
    const { selectedTab, showCheck } = this.props.docExchangeStore;
    if ((selectedTab == '0' || selectedTab == '1') && !showCheck) {
      window.openLink.openDocument(item.document_text);
    }
  }
  clickWorkflowTitle = (item) => {
    const { docExchangeStore } = this.props;
    if (!docExchangeStore.showCheck)
      allFun.forwardViewForm('requestid=' + item.subrequestid + '&f_weaver_belongto_userid=' + item.userid, (arg) => {
        docExchangeStore.getList();
      }, "portal")
  }

}

export default DocExchange;